/*
 * Copyright (c) 2009, Takashi Ito
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the authors nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "tssp_internal.h"
#include "tssp_table.h"


int tssp_table_get_payload(struct tssp_table_payload *payload,
                           const struct tssp_section *section,
                           int flags)
{
    size_t size;
    uint8_t *pos;
    const struct tssp_section *tmp = section;
    int raw = flags & TSSP_PAYLOAD_RAW;

    TSSP_ASSERT(payload);
    TSSP_ASSERT(section);

    payload->length = 0;

    /* calc payload length */
    do {
        if (raw)
            payload->length += (tmp->data.end - tmp->data.raw);
        else
            payload->length += (tmp->data.end - tmp->data.start);
        tmp = tmp->next_section;
    } while (tmp);

    if (!(flags & TSSP_PAYLOAD_DEEP) && section->next_section == NULL) {
        if (raw) {
            payload->length = section->data.end - section->data.raw;
            payload->start = section->data.raw;
        } else {
            payload->length = section->data.end - section->data.start;
            payload->start = section->data.start;
        }
        payload->end = section->data.end;
        payload->heap = NULL;
    } else {
        /* allocate memory */
        payload->heap = payload->start = malloc(payload->length);
        if (payload->heap == NULL)
            return TSSP_STATUS_MEMORY_ERROR;

        /* copy the payload of each section */
        pos = payload->start;
        tmp = section;
        do {
            if (raw) {
                size = tmp->data.end - tmp->data.raw;
                memcpy(pos, tmp->data.raw, size);
            } else {
                size = tmp->data.end - tmp->data.start;
                memcpy(pos, tmp->data.start, size);
            }
            pos += size;
            tmp = tmp->next_section;
        } while (tmp);

        payload->end = pos;
    }

    return TSSP_STATUS_OK;
}


static
void tssp_table_monitor_section_callback(int status,
                                         struct tssp_section_listener *listener,
                                         struct tssp_section *section,
                                         void *userdata)
{
    int i;
    struct tssp_table_monitor *mon = userdata;

    do {
        if (mon->discontinuity) {
            if (mon->filled == 0) {
                mon->last_number = section->last_number;
                mon->version = section->version;
                mon->extension = section->extension;
            } else {
                /* check the section params */
                if (mon->last_number < section->number)
                    break;
                if (mon->version != section->version)
                    break;
                if ((mon->extension & mon->mask) != mon->value)
                    break;
            }

            /* fill the array */
            if (mon->sections[section->number] != NULL)
                tssp_section_destroy(mon->sections[section->number]);
            else
                mon->filled++;
            mon->sections[section->number] = section;
        } else {
            /* check if the section is updated */
            if (mon->version == section->version &&
                (mon->extension & mon->mask) == mon->value)
            {
                tssp_section_destroy(section);
                return;
            }

            if (section->number > section->last_number)
                break;

            /* start filling */
            mon->discontinuity = 1;
            mon->last_number = section->last_number;
            mon->version = section->version;
            mon->extension = section->extension;
            mon->filled = 1;

            TSSP_ASSERT(mon->sections[section->number] == NULL);
            mon->sections[section->number] = section;
        }

        /* check if all the sections are obtained */
        if (mon->filled == (mon->last_number + 1)) {
            for (i = 0; i < mon->last_number; i++)
                mon->sections[i]->next_section = mon->sections[i + 1];

            /* init params */
            section = mon->sections[0];
            for (i = 0; i <= mon->last_number; i++)
                mon->sections[i] = NULL;
            mon->discontinuity = 0;
            mon->filled = 0;
            mon->last_number = 0;

            /* callback */
            mon->callback(mon, section, mon->userdata);
        }

        return;
    } while (0);

    tssp_table_monitor_reset(mon);
    tssp_section_destroy(section);
}

struct tssp_table_monitor *
tssp_table_monitor_attach(struct tssp *parser,
                          struct tssp_section_filter *filter,
                          tssp_table_monitor_callback callback,
                          void *userdata)
{
    int i;
    struct tssp_table_monitor *monitor;

    if (parser == NULL || filter == NULL || callback == NULL)
        return NULL;

    monitor = malloc(sizeof(*monitor));
    if (monitor == NULL)
        return NULL;

    monitor->parser = parser;
    monitor->discontinuity = 1;
    for (i = 0; i < TSSP_NUMELEM(monitor->sections); i++)
        monitor->sections[i] = NULL;
    monitor->filled = 0;
    monitor->last_number = 0;
    monitor->version = 0;
    monitor->extension = 0;
    monitor->mask = 0;
    monitor->value = 0;
    monitor->callback = callback;
    monitor->userdata = userdata;
    monitor->listener =
        tssp_add_section_filter(parser, filter,
                                tssp_table_monitor_section_callback,
                                monitor);

    return monitor;
}

void tssp_table_monitor_detach(struct tssp_table_monitor *monitor)
{
    if (monitor == NULL)
        return;

    TSSP_ASSERT(monitor->parser);
    TSSP_ASSERT(monitor->listener);

    tssp_remove_section_filter(monitor->parser, monitor->listener);
    tssp_table_monitor_reset(monitor);
    free(monitor);
}

void tssp_table_monitor_reset(struct tssp_table_monitor *mon)
{
    int i;

    TSSP_ASSERT(mon);

    for (i = 0; i <= mon->last_number; i++) {
        if (mon->sections[i]) {
            tssp_section_destroy(mon->sections[i]);
            mon->sections[i] = NULL;
        }
    }

    mon->discontinuity = 1;
    mon->filled = 0;
    mon->last_number = 0;
    mon->version = 0;
    mon->extension = 0;
}

void tssp_table_monitor_set_mask(struct tssp_table_monitor *monitor,
                                 uint16_t mask,
                                 uint16_t value)
{
    monitor->mask = mask;
    monitor->value = value;
}

